<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/19
 * Time: 11:29
 */

namespace Home\Model;
use Think\Model;

class OrderModel extends Model
{
    //计算运费(参数：总重量,agent_address的address_id,expressAreaname的express_id)
    public function count_freight($weight,$freight_id,$address_id){
        $agentAddress = M('agentAddress')->where( array('address_id'=>$address_id) )->find();
        $express_area_name = M('expressAreaname')->where( array('area_name'=>$agentAddress['city'],'express_id'=>$freight_id) )->find();
        if(!$express_area_name){
            $express_area_name = M('expressAreaname')->where( array('area_name'=>$agentAddress['province'],'express_id'=>$freight_id) )->find();
        }
        $express_area = M('express_area')->where( array('id'=>$express_area_name['express_area_id']) )->find();
        if($weight<=$express_area['standard']&&!empty($weight)){
            $fright_prices = $express_area['standard']*$express_area['down_num'];
        }elseif(empty($weight)){
            $fright_prices = 0;
        }else{
            $up_fright = ($weight - $express_area['standard'])*$express_area['up_num'];
            $down_fright = $express_area['standard']*$express_area['down_num'];
            $fright_prices = $up_fright + $down_fright;
        }
        return $fright_prices;
    }

    //订单参数里的商品id，商品状态，商品数量，商品规格的验证 status为表单提交或者ajax提交
    public function order_param_validate($good_idaarray,$good_statusarray,$good_numarray,$spec_str){
        //给个状态码是ajax还是表单提交，根据不同情况报错
        //商品id验证
        if (!is_array($good_idaarray)) {
            $good_idaarray = explode(",", $good_idaarray);
        }
        foreach ($good_idaarray as $g_id) {
            //商品验证
            $res_g_id = M("good")->where(array("id" => to_int($g_id)))->find();
            if (empty($res_g_id)) {
                $ajax = -1;
                return $ajax;
            }
        }

        //商品状态验证
        if (!is_array($good_statusarray)) {
            $good_statusarray = explode(",", $good_statusarray);
        }
        foreach ($good_statusarray as $g_status) {
            $status_array = array(0, 1, 2);
            if (!in_array(to_int($g_status), $status_array)) {
                $ajax = -2;
                return $ajax;
            }
        }

        //商品数量验证
        if (!is_array($good_numarray)) {
            $good_numarray = explode(",", $good_numarray);
        }
        foreach ($good_numarray as $g_num) {
            if (to_int($g_num) <= 0) {
                $ajax = -3;
                return $ajax;
            }
        }

        //验证规格
        if (!empty($spec_str)) {
            $bools = 0;
            //到下单页面多商品;隔，到确认订单多商品为数组
            if (is_array($spec_str)) {
                //多商品
                foreach ($spec_str as $ff => $gg) {
                    if(!empty($gg)){
                        $good_spec = M("good_spec")->where(array("good_id" => $good_idaarray[$ff]))->select();
                        foreach ($good_spec as $dollor => $money) {
                            $ex_spec = explode(",", $gg);
                            foreach ($ex_spec as $jay => $lie) {
                                $ex_good_spec = explode(",", $money['spec_val']);
                                if (in_array($lie, $ex_good_spec)) {
                                    $bools++;
                                }
                            }
                        }
                    }
                }
            }else {
                $spec_str = explode(",", $spec_str);
                //如果是单个商品的话
                if(is_array($good_idaarray)){
                    $good_idaarray = implode(",",$good_idaarray);
                }
                $good_spec = M("good_spec")->where(array("good_id" => $good_idaarray))->select();
                foreach ($good_spec as $gay => $gel) {
                    $good_spec_arr = explode(",", $gel['spec_val']);
                    foreach ($spec_str as $jay) {
                        if (in_array($jay, $good_spec_arr)) {
                            $bools++;
                        }
                    }
                }
                $single_good = true;
            }
            foreach ($spec_str as $jj => $kk) {
                if(!empty($kk)){
                    $spec_str_count[$jj] = count(explode(",", $kk));
                }
            }
            if(!$spec_str_count){
                $count = 0;
            }else{
                $count = array_sum($spec_str_count);
            }
            if ($bools !== $count) {
                $ajax = -4;
                return $ajax;

            }
        }
        return $single_good;

    }

    //订单总价核算(参数：商品ID，商品数量，商品状态，购物车商品id(可无),商品规格,是否是单商品状态码)
    public function order_sum_weight($good_ida,$good_num,$status,$good_aid,$spec_str,$single_good){
        //计算订单总价格（没考虑到没代理此品牌的商品）
        foreach ($good_ida as $key => $value) {
            $good = M('good')->where(array('id' => $value))->find();
            $good['good_num'] = $good_num[$key];
            $good['good_aid'] = $good_aid[$key];
            $good['status'] = $status[$key];
            if($single_good == true){
                $good['spec_str'] = $spec_str;
            }else{
                $good['spec_str'] = $spec_str[$key];
            }
            //代理是否包邮
            $is_free = agent_is_free(session("user_id"), $good['brand_id']);
            $is_agent = M("agent")->where(array("agent_id"=>session("user_id")))->getField("is_agent");
            if ($is_agent == 2) {
                //如果是普通用户
                $good['comprice'] = $good['price'];
                $total = $good['price'] * $good['good_num'];
                if ($is_free == 1 || $good['is_free'] == 1) {
                    $weight = 0;
                } else {
                    $weight = $good['weight'] * $good['good_num'];
                }
            } else {
                //如果是代理的话
                $agent_brand = M("brand")->where("id = %d", array($good['brand_id']))->getField("agent_brand");
                if ($agent_brand == 1) {//代理商品
                    //没代理此商品的品牌
                    $bool = M('agentBrand')->where(array('agent_id' => session("user_id"), 'brand_id' => $good['brand_id']))->find();
                    if (empty($bool)) {
                        $good['comprice'] = $good['price'];
                        $total = $good['price'] * $good['good_num'];
                        if ($is_free == 1 || $good['is_free'] == 1) {
                            $weight = 0;
                        } else {
                            $weight = $good['weight'] * $good['good_num'];
                        }
                    } else {
                        $good_type = $status[$key];
                        $rank_id = M('agentBrand')->where(array('agent_id' => session("user_id"), 'brand_id' => $good['brand_id']))->getField('rank_id');
                        $goodRankPrice = M('goodRankPrice')->where(array('good_id' => $value, 'rank_id' => $rank_id))->find();
                        //$good_type=1 单件   $good_type=2 整箱
                        $good['comprice'] = ($good_type == 2)?$goodRankPrice['batch_amt']:$goodRankPrice['unit_amt'];
                        $total = ($good_type == 2) ? : $goodRankPrice['unit_amt'] * $good['good_num'] ;
                        if ($is_free == 1 || $good['is_free'] == 1) {
                            $weight = 0;
                        } else {
                            $weight = ($good_type == 2) ? $good['per_num'] * $good['good_num'] * $good['weight'] : $good['weight'] * $good['good_num'];
                        }
                    }
                } else {//商家商品
                    $good['comprice'] = $good['price'];
                    $total = $good['price'] * $good['good_num'];
                    if ($is_free == 1 || $good['is_free'] == 1) {
                        $weight = 0;
                    } else {
                        $weight = $good['weight'] * $good['good_num'];
                    }
                }
            }
            $goods[]=$good;
            $sum[] = $total;
            $weight_sum[] = $weight;
        }
        $data = array("sum"=>$sum,"weight_sum"=>$weight_sum,'goods'=>$goods);
        return $data;
    }

    //下单把订单推送上级(如果没有上级,把订单推送给订单对应的的商品的任意1个品牌的最顶级代理)(参数:添加的订单id，上传的商品id）
    public function order_push($id,$good_id){
        $self = M('agent')->where(array('agent_id' => session("user_id")))->find();
        //商品是否是代理商品
        $agent_brand = is_agent_normal($good_id[0]);
        if($agent_brand == 0){
            M('order')->where(array('id' => $id))->save(array('is_platform' => 1));
        }else{
            //不是代理的话，平台发货
            if ($self["is_agent"] == 1) { // 是代理才会存在订单推送的情况
                if ($self['parent_id'] != 0) {// 有上级
                    $data = array(
                        'order_id' => $id,
                        'uid' => $self['parent_id'],
                        'state' => 0,
                        'price' => top_order_price($id, $self['parent_id'])
                    );
                    M('orderThrough')->add($data);
                } else {
                    if (!_is_director()) {//没上级,不是董事
                        $brand_id = M('good')->where(array('id' => $good_id[0]))->getField('brand_id');
                        $top_agent = top_rank($brand_id);
                        //不存在董事
                        if (!$top_agent) {
                            M('order')->where(array('id' => $id))->save(array('is_platform' => 1));
                        } else {
                            $data = array(
                                'order_id' => $id,
                                'uid' => $top_agent['agent_id'],
                                'state' => 0,
                                'price' => top_order_price($id, $top_agent['agent_id'])
                            );
                            M('orderThrough')->add($data);
                        }
                    } else {// 没上级,董事
                        M('order')->where(array('id' => $id))->save(array('is_platform' => 1));
                    }
                }
            } else {
                M('order')->where(array('id' => $id))->save(array('is_platform' => 1));
            }
        }
    }

    //
    public function order_good_stock($good_id,$number,$good_type,$spec_str,$id,$single_good){
        foreach ($good_id as $gey => $val) {
            //预减库存
              $name = M("good")->where(array("id"=>$val))->getField("g_name");
            //如果为件
              $stock = M("good")->where(array("id"=>$val))->getField("stock");
              $stock = $stock - $number[$gey];
              if($stock<0){
                  //清除订单信息以及order_good此订单id的信息
                  $data['status'] = -8;
                  $data['name'] = $name."库存不足";
                  return $data;
              }
            M('good')->where(array("id"=>$val))->setField("stock",$stock);

            $goods_price = D('Admin/Good')->goodPrice($val, $number[$gey], $good_type[$gey]);
            if ($single_good == true) {
                $spec_data = $spec_str;
            } else {
                $spec_data = $spec_str[$gey];
            }
            $res = array(
                'order_id' => $id,
                'good_id' => $val,
                'num' => $number[$gey],
                'good_type' => $good_type[$gey],
                'goods_price' => $goods_price,
                "spec_str" => serialize($spec_data),
            );
            M('orderGood')->add($res);
        };
    }

    //判断商品中是否是混搭的（good_id为数组）
    public function agent_or_normal($good_id){
        foreach ($good_id as $key => $value){
            $res  = is_agent_normal($value);
            $array[$key] = $res;
        }
        $ret = array_sum($array);
        if($ret !==0&&$ret !==count($array)){
            $bool = false;
        }else{
            $bool = true;
        }
        return $bool;
    }

}